package com.example.rizhaoscienceandtechnologymuseum.Server;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;


import com.example.rizhaoscienceandtechnologymuseum.View.MainActivity;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class AppRestartService extends Service implements Runnable
{
    public static boolean isOnForeground = true;
    public static boolean isCloseFlag = false;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        isCloseFlag = false;
        new Thread(this).start();
    }
    public void setIsCloseFlag(boolean isCloseFlag){
        this.isCloseFlag = isCloseFlag;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void run() {
        while(!isCloseFlag){
            boolean isOnForegroundNew = isRunningOnForeground(this);

            if(isOnForegroundNew != isOnForeground){
                toFront();
            }
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static boolean isRunningOnForeground(Context context){

        ActivityManager acm = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if(acm != null){
            List<ActivityManager.RunningAppProcessInfo> runApps = acm.getRunningAppProcesses();
            if(runApps != null && !runApps.isEmpty()){
                for(ActivityManager.RunningAppProcessInfo app : runApps){
                    if(app.processName.equals(context.getPackageName())){
                        if(app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    private void toFront()
    {
        //获取ActivityManager
        ActivityManager mAm = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        //获得当前运行的task
        /*List<ActivityManager.RunningTaskInfo> taskList = mAm.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo rti : taskList) {
            //找到当前应用的task，并启动task的栈顶activity，达到程序切换到前台
            if (rti.topActivity.getPackageName().equals(getPackageName())) {
                mAm.moveTaskToFront(rti.id, 0);
                return;
            }
            rti.topActivity.getPackageName().equals(getPackageName())
        }*/
        List<ActivityManager.RunningAppProcessInfo> pis = mAm.getRunningAppProcesses();
        ActivityManager.RunningAppProcessInfo topAppProcess = pis.get(0);
        if (topAppProcess != null && topAppProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            if(topAppProcess.processName.equals(getPackageName())){
                mAm.moveTaskToFront(topAppProcess.pid,0);
            }
        }
        //若没有找到运行的task，用户结束了task或被系统释放，则重新启动mainactivity
        Intent resultIntent = new Intent(this, MainActivity.class);
        resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(resultIntent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
